package com.yserp.project.erp.store.stock.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.yserp.common.exception.BusinessException;
import com.yserp.common.utils.StringUtils;
import com.yserp.common.utils.mybatis.MybatisPlusUtil;
import com.yserp.common.utils.security.ShiroUtils;
import com.yserp.project.erp.store.instorelog.domain.StockInLog;
import com.yserp.project.erp.store.instorelog.service.IStockInLogService;
import com.yserp.project.erp.store.outstorelog.domain.StockOutLog;
import com.yserp.project.erp.store.outstorelog.service.IStockOutLogService;
import com.yserp.project.erp.store.stock.domain.Stock;
import com.yserp.project.erp.store.stock.mapper.StockMapper;
import com.yserp.project.erp.store.stock.service.IStockService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.util.List;

/**
 * 商品库存信息Service业务层处理
 *
 * @author yserp
 * @date 2022-07-01
 */
@Service
public class StockServiceImpl extends ServiceImpl<StockMapper, Stock> implements IStockService {
    @Resource
    private StockMapper stockMapper;
    @Autowired
    private IStockInLogService stockInLogService;
    @Autowired
    private IStockOutLogService stockOutLogService;


    /**
     * 查询商品库存信息列表
     *
     * @param stock 商品库存信息
     * @return 商品库存信息
     */
    @Override
    public List<Stock> selectStockList(Stock stock) {
        QueryWrapper<Stock> queryWrapper = new QueryWrapper<>();
        MybatisPlusUtil.notNullField(stock, queryWrapper);
        return stockMapper.selectList(queryWrapper);
    }

    @Override
    public List<Stock> selectStockListByBatchNoNull(Stock stock) {
        QueryWrapper<Stock> queryWrapper = new QueryWrapper<>();
        MybatisPlusUtil.notNullField(stock, queryWrapper);
        //单独对批次空值处理
        if(StringUtils.isBlank(stock.getBatchNo())){
            queryWrapper.eq("batch_no","");
        }
        return stockMapper.selectList(queryWrapper);
    }


    @Override
    @Transactional
    public int inStock(Stock stock, StockInLog stockInLog) {
        int result = 0;
        if (null == stock || null == stockInLog) {
            throw new BusinessException("库存变更失败");
        }
        //1.库存处理
        Stock query = new Stock();
        query.setBatchNo(stock.getBatchNo());
        query.setWarehouseId(stock.getWarehouseId());
        query.setGoodsId(stock.getGoodsId());
        List<Stock> stocks = selectStockListByBatchNoNull(query);
        boolean stockFlag = false;
        if (CollectionUtils.isEmpty(stocks)) {
            stock.setCreateBy(ShiroUtils.getLoginName());
            stockFlag = this.save(stock);
        } else {
            int size = stocks.size();
            if (1 == size) {
                Stock queryStock = stocks.get(0);
                Stock upStock = new Stock();
                upStock.setId(queryStock.getId());
                upStock.setUpdateBy(ShiroUtils.getLoginName());
                BigDecimal stockNumber = queryStock.getStockNumber().add(stock.getStockNumber());
                upStock.setStockNumber(stockNumber);
                stockFlag = this.updateById(upStock);
            } else {
                throw new BusinessException("存在多条相同类型的库存记录");
            }
        }

        //2.日志处理
        int j = stockInLogService.insertStockInLog(stockInLog);
        if (stockFlag && j > 0) {
            result = 1;
        }
        return result;
    }

    @Override
    @Transactional
    public int outStock(Stock stock, StockOutLog stockOutLog) {
        int result = 0;
        if (null == stock || null == stockOutLog) {
            throw new BusinessException("库存变更失败");
        }
        //1.库存处理
        Stock query = new Stock();
        query.setBatchNo(stock.getBatchNo());
        query.setWarehouseId(stock.getWarehouseId());
        query.setGoodsId(stock.getGoodsId());
        List<Stock> stocks = this.selectStockList(query);
        boolean stockFlag = false;
        if (CollectionUtils.isEmpty(stocks)) {
            throw new BusinessException("商品：" + stock.getGoodsName() + ",没有库存,请关注库存信息");
        } else {
            int size = stocks.size();
            if (1 == size) {
                Stock queryStock = stocks.get(0);
                BigDecimal stockNumber = queryStock.getStockNumber();
                BigDecimal outNumber = stock.getStockNumber();
                if (stockNumber.compareTo(outNumber)<0) {
                    throw new BusinessException("商品：" + queryStock.getGoodsName() + "库存数量不足");
                }
                Long id = queryStock.getId();
                BigDecimal exitNumber =stockNumber.subtract(outNumber);
                //判断库存是否已经没有了
                if(exitNumber.compareTo(BigDecimal.ZERO)==0){
                    stockFlag = this.removeById(id);
                }else {
                    Stock upStock = new Stock();
                    upStock.setId(id);
                    upStock.setStockNumber(exitNumber);
                    stockFlag = this.updateById(upStock);
                }
            } else {
                //出库数据
                BigDecimal outNumber = stock.getStockNumber();
                BigDecimal allNumber =stocks.stream().map(Stock::getStockNumber).reduce(BigDecimal.ZERO,BigDecimal::add);
                if (allNumber.compareTo(outNumber)<0) {
                    throw new BusinessException("商品：" + stock.getGoodsName() + "库存数量不足");
                }
                for (Stock item : stocks) {
                    BigDecimal stockNumber = item.getStockNumber();
                    Long id = item.getId();
                    if(outNumber.compareTo(stockNumber)>0){
                        this.removeById(id);
                        outNumber=outNumber.subtract(stockNumber);
                    }else if(outNumber.compareTo(stockNumber)==0){
                        this.removeById(item.getId());
                        break;
                    }else{
                        BigDecimal exitNumber = stockNumber.subtract(outNumber);
                        Stock upStock = new Stock();
                        upStock.setId(id);
                        upStock.setStockNumber(exitNumber);
                        stockFlag = this.updateById(upStock);
                        break;
                    }

                }
            }
        }

        //2.日志处理
        boolean logFlag = stockOutLogService.save(stockOutLog);
        if (stockFlag && logFlag) {
            result = 1;
        }
        return result;
    }



}
